﻿
using Aop.Api.Domain;
using JinfuyuanProject.Entity;
using JinfuyuanProject.Repository.Interface;
using JinfuyuanProject.Repository;
using JinfuyuanProject.Service;
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace JinfuyuanProject.Hubs
{
    [HubName("myChatHub")]
    public class MyChatHub : Hub
    {
       
        JinfuyuanDbContext db = new JinfuyuanDbContext();
        IProductRepository productRepository = new ProductRepository(new JinfuyuanDbContext());
        IProductApplicationRepository ProductApplication=new ProductApplicationRepository(new JinfuyuanDbContext());
        IContractRepository contractRepository = new ContractRepository(new JinfuyuanDbContext());
        IExpenseRecordRepository expenseRecordRepository = new ExpenseRecordRepository(new JinfuyuanDbContext());

        //  {张三:  1111},{李四:2222},{王五:33333}
        public static Dictionary<string, string> dic = new Dictionary<string, string>();
        /// <summary>
        /// 推送至所有客户端
        /// </summary>
        /// <param name="message">消息</param>
        public void Send(string account)
        {
            //调用所有客户端的SendMessage方法
            Clients.All.SendMessage($"大家好，欢迎{account}登录聊天室");
        }
        public void LoginChat(string account)
        {

            //把当前登录人的名字当key
            if (dic.Where(x => x.Key == account).Count() == 0)
            {
                dic[account] = Context.ConnectionId;
            }
            //服务给客户端推广播
            string result = "";
            List<string> nameList = dic.Select(x => x.Key).ToList();
            foreach (string name in nameList)
            {
                result += name + ",";
            }
            result = result.Substring(0, result.Length - 1);
            Clients.All.UpdateUserList(result);
        }
        public void PrivateChatToAccount(string message, string sendAccount, string reviceAccount)
        {
            string reviceConnnectionId = dic.Where(x => x.Key == reviceAccount).Select(x => x.Value).FirstOrDefault();
            if (!string.IsNullOrEmpty(reviceConnnectionId))
            {
                //给某个用户发送内容
                Clients.Client(reviceConnnectionId).RevPrivateMessage(sendAccount + "对你说：" + message);
            }

        }
        public void SendAllStudent()
        {
            //所有的学生数据
            ProductService productService = new ProductService(productRepository,db,ProductApplication,contractRepository, expenseRecordRepository);
            List<JinfuyuanProject.Entity.Product> list = productService.GetData();
            Clients.All.RevStudents(Newtonsoft.Json.JsonConvert.SerializeObject(list));
        }
    }
}